package org.apache.struts2.plugin.json;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.inject.Inject;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsConstants;
import org.apache.struts2.dispatcher.StrutsResultSupport;
import org.apache.struts2.plugin.json.model.JSONValue;
import org.apache.struts2.plugin.json.reflection.Reflection;
import org.apache.struts2.plugin.json.writer.AbstractJSONWriter;
import org.apache.struts2.plugin.json.writer.JSONWriterFactory;

/**
 * Result use into struts for permit to an action to be converted intro JSON.
 * @author VERDOÏA Laurent <verdoialaurent@gmail.com>
 */
public class JSONResult extends StrutsResultSupport {

    private static final long serialVersionUID = -6290402909791372115L;
    /**
     * Current encoding, by default set to the default
     * {@link StrutsConstants#STRUTS_I18N_ENCODING struts encoding}.
     */
    private String encoding = StrutsConstants.STRUTS_I18N_ENCODING;

    /**
     * Define the encoding of the response.<br />
     * The encoding is injected via 
     * {@link StrutsConstants#STRUTS_I18N_ENCODING StrutsConstants.STRUTS_I18N_ENCODING}.
     * @param encoding
     */
    @Inject(StrutsConstants.STRUTS_I18N_ENCODING)
    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }

    /**
     * Return the encoding of the response.
     * @return Encoding of response
     */
    public String getEncoding() {
        return encoding;
    }

    /**
     * Execute the transofrmation ofthe action into JSON
     * @param finalLocation Not used but need by {@link StrutsResultSupport}
     * @param invocation Action to transform into JSON
     * @throws java.io.IOException Just follow up
     * @throws org.apache.struts2.plugin.json.writer.JSONException Just follow up
     */
    @Override
    protected void doExecute(String finalLocation, ActionInvocation invocation)
            throws Exception {
        HttpServletResponse response = ServletActionContext.getResponse();
        Object rootObject = invocation.getAction();

        response.setContentType("application/json;charset=" + encoding);
        ServletOutputStream out = response.getOutputStream();

        JSONValue j = Reflection.reflection(rootObject);
        AbstractJSONWriter w = JSONWriterFactory.create(j, out);
        w.write();
    }
}
